package com.ylz.sjzx.sio.room.service.impl;

import com.ylz.sjzx.sio.sdk.client.core.IMNioBase;
import com.ylz.sjzx.sio.sdk.client.service.UserSessionService;
import com.ylz.sjzx.sio.sdk.client.session.UserSession;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.ConcurrentHashMap;

/**
 * userInfo进程Session
 * 分布式的话会有分布式session
 *
 * @author sqy
 * @version 1.0
 * @date 2021/2/23
 */
@Slf4j
@Service(value = "userL2SessionServiceImpl")
public class UserL2SessionServiceImpl implements UserSessionService {

    @Resource(name = "userL1SessionServiceImpl")
    private UserSessionService userL1SessionService;

    private ConcurrentHashMap<String, UserSession> sessions = IMNioBase.getGlobalUserSession();

    @Override
    @SneakyThrows
    public void save(UserSession session) {
        //todo 并发处理
        //判断是否存在userId
        if (null == session || StringUtils.isBlank(session.getUserId())) {
            return;
        }
        //判断是否已存在,如果存在不进行操作因为一个user只能有一个l2Session,属于同一个引用
        if (sessions.containsKey(session.getUserId())) {
            return;
        }
        sessions.put(session.getUserId(), session);
        //目前不需要保存
//        userL1SessionService.save(session);
    }

    @Override
    @SneakyThrows
    public UserSession getByUserId(String uid) {
        return sessions.get(uid);
    }

    @Override
    @SneakyThrows
    public UserSession getOrAddByUserId(String uid) {
        UserSession userSession = sessions.get(uid);
        if (null == userSession) {
            userSession = new UserSession();
            userSession.setUserId(uid);
            this.save(userSession);
        }
        return userSession;
    }
}
